package okw.gui.dialogs;

import okw.database.DatabaseManager;
import okw.database.Terminal;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridData;

public class DlgTerminalAddEdit extends Dialog {
	private Terminal terminal;
	private boolean edit;
	
	private Text txtNazwa;
	private Text txtIdentyfikator;

	/**
	 * Create the dialog.
	 * 
	 * @param shell
	 */
	public DlgTerminalAddEdit(Shell shell, Terminal terminal, boolean edit) {
		super(shell);
		
		this.edit = edit;
		this.terminal = terminal;
	}

	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		container.setLayout(new GridLayout(2, false));

		Label lblNazwa = new Label(container, SWT.NONE);
		lblNazwa.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblNazwa.setText("Nazwa:");

		txtNazwa = new Text(container, SWT.BORDER);
		txtNazwa.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		txtNazwa.setText(!edit ? "" : terminal.getName());

		Label lblIdentyfikator = new Label(container, SWT.NONE);
		lblIdentyfikator.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER,
				false, false, 1, 1));
		lblIdentyfikator.setText("Identyfikator:");

		txtIdentyfikator = new Text(container, SWT.BORDER);
		txtIdentyfikator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		txtIdentyfikator.setText(!edit ? "" : terminal.getIdentificationField());

		return container;
	}

	/**
	 * Create contents of the button bar.
	 * 
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, edit ? "Edytuj" : "Dodaj",
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				"Anuluj", false);
	}

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 300);
	}

	// TODO: ustawic w pozostalych oknach
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText(edit ? "Edytuj terminal" : "Dodaj terminal");
	}
	
	protected void okPressed() {
		terminal.setName(txtNazwa.getText());
		terminal.setIdentificationField(txtIdentyfikator.getText());
		if(edit == false) {
			DatabaseManager.getInstance().save(terminal);
		} else {
			DatabaseManager.getInstance().update(terminal);
		}
		
		super.okPressed();
	}
}
